package main

import (
	"fmt"
	"k8s.io/client-go/kubernetes"
	"volcano.sh/volcano/pkg/scheduler/framework"
	"volcano.sh/volcano/pkg/scheduler/plugins/util"
)

const PluginName = "prebind-plugin"

type PreBindPlugin struct {
	kubeClient kubernetes.Interface
}

func (p *PreBindPlugin) Name() string {
	return PluginName
}

// Volcano 1.6 插件生命周期方法
func (p *PreBindPlugin) OnSessionOpen(ssn *framework.Session) {
	p.kubeClient = ssn.KubeClient()
	pl := util.NewPodListerFromNode(ssn)
	nodeMap := util.GenerateNodeMapAndSlice(ssn.Nodes)
	// 正确方法：通过 AddEventHandler 注册到 Allocate 阶段
	ssn.AddEventHandler(&framework.EventHandler{
		AllocateFunc: func(event *framework.Event) {
			pod := pl.GetPod(event.Task)
			if pod == nil {
				fmt.Errorf("PreBindPlugin: Pod %s/%s not found", event.Task.Namespace, event.Task.Name)
				return
			}
			node, ok := nodeMap[event.Task.NodeName]
			if !ok {
				fmt.Errorf("PreBindPlugin: Node %s not found", event.Task.NodeName)
				return
			}
			k8sNode := node.Node()
			fmt.Printf("[PreBindPlugin] Task %s/%s on node %s passed checks\n", pod.Namespace, pod.Name, k8sNode.Name)
		},
		DeallocateFunc: func(event *framework.Event) {
			return
		},
	})
}

func (p *PreBindPlugin) OnSessionClose(ssn *framework.Session) {}

// 插件工厂函数（参数需匹配 Volcano 1.6 接口）
func New(_ framework.Arguments) framework.Plugin {
	return &PreBindPlugin{}
}
